﻿using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.MSBuild.Tools.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace NuGet.MSBuild.Tools
{
    public class ResolveNuGetToolPath : Task
    {
        [Required]
        public string SolutionPath { get; set; }

        [Output]
        public string ToolPath { get; set; }

        public override bool Execute()
        {
            string fileName = Path.Combine(this.SolutionPath, SpecialFolder.NuGetRoot, SpecialFile.Packages);
            if (File.Exists(fileName))
            {
                string result = null;

                PackageConfigReader reader = new PackageConfigReader();

                var packages = reader.Read(fileName);
                if (packages != null && packages.Any())
                {
                    var package = (from o in packages
                                   where o.Id == PackageId.NuGetCommandLine
                                   select o).SingleOrDefault();
                    if (package != null)
                    {
                        result = Path.Combine(
                            this.SolutionPath,
                            SpecialFolder.Packages,
                            string.Format("{0}.{1}", package.Id, package.Version),
                            SpecialFolder.Tools);
                    }

                    if (!string.IsNullOrEmpty(result))
                    {
                        this.ToolPath = result;
                    }
                }
            }

            return true;
        }
    }
}
